<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/2/25
 * Time: 12:31
 */

namespace app\index\controller;

use app\common\controller\HomeBase;
use app\common\model\Article as ArticleModel;
use app\common\model\BoolStatus;
use think\Cache;
use app\common\model\FavoritesItem;

class Item extends HomeBase
{
    /**
     * 文章缓存前缀
     * @var string
     */
    private $_cachePrefix = 'article_';

    /**
     * 缓存有效期
     * @var int
     */
    private $_cacheExpire = 3600;

    /**
     * 文章详情页入口
     * @param int $id 文章编号
     * @return mixed
     */
    public function index($id = 1)
    {
        if (!$id) {
            $this->error('404');
        }
        $articleModel = new ArticleModel();
        $article = Cache::get($this->_cachePrefix.$id);
        if (!$article) {
            $article = $articleModel::has('detail')
                ->where('status', '=', BoolStatus::OPEN)
                ->find($id);
            if (!$article) {
                $this->error('404');
            }
            Cache::set($this->_cachePrefix.$id, $article, $this->_cacheExpire);
        }
        if (!$article->status) {
            $this->error('404');
        }
        $this->assign('article', $article);

        //下一页
        $next = $articleModel->where('id', '>', $id)
            ->where('status', '=', BoolStatus::OPEN)
            ->order('id', 'asc')
            ->field(['id', 'subject'])
            ->find();

        $this->assign('next', $next);

        //上一页
        $prev = $articleModel->where('id', '<', $id)
            ->where('status', '=', BoolStatus::OPEN)
            ->order('id', 'desc')
            ->field(['id', 'subject'])
            ->find();

        $this->assign('prev', $prev);

        $recommendGoodsList = (new FavoritesItem())->getRandRecommendData(4);
        $this->assign('recommendGoodsList', $recommendGoodsList);

        $this->setSEOInfo($article->subject, $article->seo_keywords, $article->seo_desc);
        return $this->fetch('item/index');
    }

    /**
     * 获取访问量
     * @param int $id
     */
    public function getVisit($id = 1)
    {
        $articleModel = new ArticleModel();
        $articleModel->where('id', '=', $id)->setInc('viewed');
        $articleModel = $articleModel->find($id);
        return json([$articleModel->viewed]);
    }

}